import 'package:dio/dio.dart';
import '../models/base_response.dart';

enum Method { get, post }

class RequestManager {
  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";

  factory RequestManager() => _getInstance();

  static RequestManager get instance => _getInstance();

  static RequestManager _instance;

  Dio dio;

  RequestManager._internal() {
    // 初始化
    Map<String, dynamic> headers = Map();
    headers['Authorization'] = "Bearer 05be0995-295d-497f-bdfb-92cb30a4312b";
    dio = Dio(BaseOptions(
        connectTimeout: 5000, receiveTimeout: 10000, headers: headers));
  }

  static RequestManager _getInstance() {
    if (_instance == null) {
      _instance = RequestManager._internal();
    }
    return _instance;
  }

  Future<BaseResponse> get(String url, {Map<String, dynamic> params}) {
    return _doRequestManager(url, params, Method.get);
  }

  Future<BaseResponse> post(String url, {Map<String, dynamic> params}) {
    return _doRequestManager(url, params, Method.post);
  }

  // ignore: missing_return
  Future<BaseResponse> _doRequestManager(
      String url, Map<String, dynamic> params, Method method) async {
    try {
      Response response;
      switch (method) {
        case Method.get:
          if (params != null && params.isNotEmpty) {
            response = await dio.get(url, queryParameters: params);
          } else {
            response = await dio.get(url);
          }
          break;
        case Method.post:
          if (params != null && params.isNotEmpty) {
            response = await dio.post(url, queryParameters: params);
          } else {
            response = await dio.post(url);
          }
          break;
      }

      // print('''url: $url\n response: ${response}''');

      if (response.statusCode != 200) {
        return BaseResponse(response.statusCode, "请求失败", Map());
      }
      return BaseResponse.fromJson(response.data);
    } catch (exception) {
      print('''exception : ${exception.toString()}''');
      Map map = Map<String, dynamic>();
      map['error'] = exception.toString();
      return BaseResponse(-1, "请求失败", map);
    }
  }
}
